<template>
	<div class="uploadImgComponent">
		<el-upload class="upload-demo" ref="upload" action="" :auto-upload="false" :on-change='changeUpload' :on-remove="handleRemove">
			<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
			<el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
			<div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过5mb</div>
		</el-upload>
	</div>
</template>

<script>
	import config from '@/assets/js/config.js'
	export default {
		data(){
			return {
				upImg:config.upImg,
				formData: new FormData(),
				fileList: []
			}
		},
		props:["clearImgList"],
		methods:{
			handleRemove(file, fileList) {
		        this.fileList = fileList;
		    },
		    changeUpload(file, fileList){
				this.fileList = fileList;
//				this.formData.append("files",file.raw);
			},
			submitUpload(){
//				console.log(this.fileList);
				if(this.fileList.length>1){
					this.$confirm('上传图片数量不能超过1张', '提示', {
				        confirmButtonText: '确定',
				        showCancelButton:false,
				        type: 'warning'
			        })
				}else{
					var that = this;
					this.fileList.forEach(function (file) {
		                that.formData.append('files', file.raw);
		            })
					this.$submit.post(this.upImg,this.formData).then((res)=>{
						console.log(res);
						this.$emit("toparent",res.data.data.img_url);
						this.$message('图片上传成功');
						for (var key of this.formData.keys()){
						    this.formData.delete(key);
						};
					})
				}
			}
			
		    
		},
		watch:{
			clearImgList:function(){
				console.log(this.clearImgList);
				if(this.clearImgList){
					this.$refs.upload.clearFiles();
				}
			}
		}
		
	}
</script>

<style>
	
</style>